﻿using JsonConversion;
using Newtonsoft.Json;
using RTracker.Models.Common;
using RTracker.Models.ErrorLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace RTracker.Areas.Recruitment.Models.Candidate
{
    public class MCandidate
    {
        /// static variable RowSize from config settings to get list of this row size.
        public static int nRowSize = Convert.ToInt32(ConfigurationManager.AppSettings["TotalRecordsInListUser"]);
        
        /// <summary>
        /// This method is used to create a candidate in the database.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCCandidate">This object contains details of the candidate.</param>
        /// <returns>CStatus which is an object that contain transaction details</returns>
        public CStatus CreateCandidate(CAuthenticationContext objCAuthenticationContext, ref CCandidate objCCandidate)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_create_candidate_procedure");
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Connection = con;
                    cmd.Parameters.Add("@organization_id", SqlDbType.Int).Value = objCCandidate.OrganizationId;
                    cmd.Parameters.Add("@first_name", SqlDbType.NVarChar).Value = objCCandidate.FirstName;
                    cmd.Parameters.Add("@middle_name", SqlDbType.NVarChar).Value = objCCandidate.MiddleName;
                    cmd.Parameters.Add("@last_name", SqlDbType.NVarChar).Value = objCCandidate.LastName;
                    cmd.Parameters.Add("@contact_address", SqlDbType.NVarChar).Value = objCCandidate.ContactAddress;
                    cmd.Parameters.Add("@email_id", SqlDbType.NVarChar).Value = objCCandidate.EmailId;
                    cmd.Parameters.Add("@mobile", SqlDbType.NVarChar).Value = objCCandidate.Mobile;
                    cmd.Parameters.Add("@landline", SqlDbType.NVarChar).Value = objCCandidate.Landline;
                    cmd.Parameters.Add("@source", SqlDbType.Int).Value = objCCandidate.Source;
                    cmd.Parameters.Add("@reference_by", SqlDbType.NVarChar).Value = objCCandidate.ReferenceBy;
                    cmd.Parameters.Add("@department", SqlDbType.Int).Value = objCCandidate.Department;
                    cmd.Parameters.Add("@skills", SqlDbType.NVarChar).Value = objCCandidate.Skills;
                    cmd.Parameters.Add("@expirence", SqlDbType.Int).Value = objCCandidate.Expirence;
                    cmd.Parameters.Add("@resume", SqlDbType.VarBinary).Value = DBNull.Value;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCAuthenticationContext.UserId;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }

                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }

            return oCStatus;
        }

        /// <summary>
        /// This method is used to delete a candidate in the database.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCUser">This object contains details of the cadidate.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus DeleteCandidate(CAuthenticationContext objCAuthenticationContext, ref CCandidate objCCandidate)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_delete_candidate_procedure");
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCAuthenticationContext.UserId;
                    cmd.Parameters.Add("@candidate_ids", SqlDbType.NVarChar).Value = objCCandidate.CandidateIds;
                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }

            return oCStatus;
        }

        /// <summary>
        /// This method is used to update the candidate's detail in the database.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCCandidate">This object contains details of the candidate.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus UpdateCandidate(CAuthenticationContext objCAuthenticationContext, ref CCandidate objCCandidate)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_update_candidate_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;

                    cmd.Parameters.Add("@candidate_id", SqlDbType.Int).Value = objCCandidate.CandidateId;
                    cmd.Parameters.Add("@organization_id", SqlDbType.Int).Value = objCCandidate.OrganizationId;
                    cmd.Parameters.Add("@first_name", SqlDbType.NVarChar).Value = objCCandidate.FirstName;
                    cmd.Parameters.Add("@middle_name", SqlDbType.NVarChar).Value = objCCandidate.MiddleName;
                    cmd.Parameters.Add("@last_name", SqlDbType.NVarChar).Value = objCCandidate.LastName;
                    cmd.Parameters.Add("@contact_address", SqlDbType.NVarChar).Value = objCCandidate.ContactAddress;
                    cmd.Parameters.Add("@email_id", SqlDbType.NVarChar).Value = objCCandidate.EmailId;
                    cmd.Parameters.Add("@mobile", SqlDbType.NVarChar).Value = objCCandidate.Mobile;
                    cmd.Parameters.Add("@landline", SqlDbType.NVarChar).Value = objCCandidate.Landline;
                    cmd.Parameters.Add("@source", SqlDbType.Int).Value = objCCandidate.Source;
                    cmd.Parameters.Add("@reference_by", SqlDbType.NVarChar).Value = objCCandidate.ReferenceBy;
                    cmd.Parameters.Add("@department", SqlDbType.Int).Value = objCCandidate.Department;
                    cmd.Parameters.Add("@skills", SqlDbType.NVarChar).Value = objCCandidate.Skills;
                    cmd.Parameters.Add("@expirence", SqlDbType.Int).Value = objCCandidate.Expirence;
                    cmd.Parameters.Add("@resume", SqlDbType.VarBinary).Value = DBNull.Value;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCAuthenticationContext.UserId;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        /// This method is used to get the candidate detail from the database;
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCCandidate">This object contains details of the candidate.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus GetCandidateDetail(CAuthenticationContext objCAuthenticationContext, ref CCandidate objCCandidate)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    SqlCommand cmd = new SqlCommand("r_get_candidate_detail_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;

                    cmd.Parameters.Add("@candidate_id", SqlDbType.Int).Value = objCCandidate.CandidateId;
                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;

                    SqlDataAdapter adp = new SqlDataAdapter(cmd);

                    DataTable dt = new DataTable();

                    int rowsAffected = adp.Fill(dt);

                    if (rowsAffected > 0)
                    {
                        objCCandidate = dt.ConvertToListFromDataTableCandidate()[0];
                    }

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.DetailSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        /// This function is used to get complete Candidates list
        /// </summary>
        /// <returns>List of type CCandidate</returns>
        public GCandidate GetCandidateGridList(CCandidate objCCandidate, CAuthenticationContext objCAuthenticationContext)
        {
            GCandidate objGCandidate = new GCandidate();
            int nTotalRecords = 0;
            int nCurrentRowSize = nRowSize;

            if (objCCandidate.RowSize != 0)
            {
                nCurrentRowSize = objCCandidate.RowSize;
            }
            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    SqlCommand cmd = new SqlCommand("r_get_candidate_paging_list_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@candidate_id", SqlDbType.Int).Value = objCCandidate.CandidateId;
                    cmd.Parameters.Add("@organization_id", SqlDbType.Int).Value = objCCandidate.OrganizationId;
                    cmd.Parameters.Add("@page_number", SqlDbType.Int).Value = objCCandidate.PageNumber;
                    cmd.Parameters.Add("@row_size", SqlDbType.Int).Value = nCurrentRowSize;
                    cmd.Parameters.Add("@sort_on", SqlDbType.VarChar).Value = objCCandidate.SortOn;
                    cmd.Parameters.Add("@sort_type", SqlDbType.VarChar).Value = objCCandidate.SortType;
                    cmd.Parameters.Add("@search", SqlDbType.VarChar).Value = objCCandidate.Search;
                    cmd.Parameters.Add("@searchon", SqlDbType.VarChar).Value = objCCandidate.SearchOn;
                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;
                    SqlDataAdapter adp = new SqlDataAdapter(cmd);

                    DataTable dt = new DataTable();

                    int rowsAffected = adp.Fill(dt);

                    objGCandidate.Paging = new CPaging();
                    if (rowsAffected > 0)
                    {
                        objGCandidate.LstCandidate = dt.ConvertToListFromDataTableCandidate();
                        objGCandidate.LstCandidate[0].PageNumber = int.Parse(cmd.Parameters["@idOut"].Value.ToString());
                        objGCandidate.Paging.PageNumber = objGCandidate.LstCandidate[0].PageNumber;
                    }
                    else
                    {
                        objGCandidate.LstCandidate = null;
                    }

                    nTotalRecords = int.Parse(cmd.Parameters["@error"].Value.ToString());

                    objGCandidate.Status = new CStatus();

                    if (nTotalRecords < 0)
                    {
                        objGCandidate.Status.Success = false;
                        objGCandidate.Status.StatusDetails = nTotalRecords.DbError();
                    }
                    else
                    {
                        objGCandidate.Paging.TotalRecordsCount = nTotalRecords;
                        objGCandidate.Paging.PageSize = nCurrentRowSize;

                        objGCandidate.Status.Success = true;
                        objGCandidate.Status.StatusDetails = "success";
                    }
                }
                catch (Exception ex)
                {
                    objGCandidate.Status = new CStatus();
                    objGCandidate.Status.Success = false;
                    objGCandidate.Status.StatusDetails = ex.Message;
                }
            }
            return objGCandidate;
        }
        /// <summary>
        /// Sets the softlock on the record whose Id is passed.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCCandidate">This object contains details of the candidate.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus SetCandidateSoftLock(CAuthenticationContext objCAuthenticationContext, CCandidate objCCandidate)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_set_candidate_soft_lock_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@candidate_id", SqlDbType.NVarChar).Value = objCCandidate.CandidateId;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCAuthenticationContext.UserId;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }


            return oCStatus;
        }

        /// <summary>
        /// Sets the hardlock on the record whose Id is passed.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCCandidate">This object contains details of the candidate.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus SetCandidateHardLock(CAuthenticationContext objCAuthenticationContext, CCandidate objCCandidate)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_set_candidate_hard_lock_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@candidate_id", SqlDbType.NVarChar).Value = objCCandidate.CandidateId;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCCandidate.CreatedBy;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        /// Releases the softlock on the record whose Id is passed.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCCandidate">This object contains details of the candidate.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus ReleaseCandidateSoftLock(CAuthenticationContext objCAuthenticationContext, CCandidate objCCandidate)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_release_candidate_soft_lock_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@candidate_id", SqlDbType.NVarChar).Value = objCCandidate.CandidateId;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCCandidate.CreatedBy;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }

        /// <summary>
        /// Releases the hardlock on the record whose Id is passed.
        /// </summary>
        /// <param name="objCAuthenticationContext">This object contains information about user's authentication context.</param>
        /// <param name="objCCandidate">This object contains details of the candidate.</param>
        /// <returns>CStatus which is an object that contain transaction details.</returns>
        public CStatus ReleaseCandidateHardLock(CAuthenticationContext objCAuthenticationContext, CCandidate objCCandidate)
        {
            CStatus oCStatus = new CStatus();

            using (SqlConnection con = new SqlConnection(CCommonCollection.ConnectionString))
            {
                try
                {
                    con.Open();
                    SqlCommand cmd = new SqlCommand("r_release_candidate_hard_lock_procedure", con);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Add("@candidate_id", SqlDbType.NVarChar).Value = objCCandidate.CandidateId;
                    cmd.Parameters.Add("@created_by", SqlDbType.Int).Value = objCCandidate.CreatedBy;

                    cmd.Parameters.Add("@idOut", SqlDbType.Int).Value = null;
                    cmd.Parameters["@idOut"].Direction = ParameterDirection.Output;
                    cmd.Parameters.Add("@error", SqlDbType.Int).Value = null;
                    cmd.Parameters["@error"].Direction = ParameterDirection.Output;

                    cmd.ExecuteNonQuery();

                    if (Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()) > 0)
                    {
                        oCStatus.Success = true;
                        oCStatus.StatusDetails = CAppConstants.SessionSuccess;
                    }
                    else
                    {
                        oCStatus.Success = false;
                        oCStatus.StatusDetails = Convert.ToInt32(cmd.Parameters["@idOut"].Value.ToString()).DbError();
                    }
                }
                catch (Exception ex)
                {
                    oCStatus.Success = false;
                    oCStatus.StatusDetails = ex.Message;
                }
            }
            return oCStatus;
        }
    }
}